
//
//  HotPostTableViewController.m
//  DFForum
//
//  Created by lanou on 15/10/23.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "HotPostTableViewController.h"
#import "HotPostTableViewCell.h"
#import "HotPost.h"
#import "PKRequestManager.h"
#import "UIImageView+WebCache.h"
#import "DFwebViewController.h"
#import "CommonTableViewCell.h"
#import "MJRefresh.h"
#import "FMDatabase.h"
#import "DFSignlTon.h"
@interface HotPostTableViewController ()<UITabBarDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, assign) int page;

@property (nonatomic, strong) FMDatabase *dataBase;
@end

@implementation HotPostTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _dataSourceArray = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[HotPostTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self requestDataWithType:0];
    self.tableView.rowHeight = 182;
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestDataWithType:0];
    }];
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self requestDataWithType:1];
    }];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"DFront.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        [_dataBase executeUpdate:@"CREATE TABLE HOTPOST (title text,photo text,nickname text,reply text,lastdate text,wdate text,bbsname text)"];
    }
    else
    {
        NSLog(@"打开数据库失败");
    }
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM HOTPOST"];
    while ([resultSet next]) {
        NSString *title = [resultSet stringForColumn:@"title"];
        NSString *photo = [resultSet stringForColumn:@"photo"];
        NSString *nickname = [resultSet stringForColumn:@"nickname"];
        NSString *reply = [resultSet stringForColumn:@"reply"];
        NSString *lastdate = [resultSet stringForColumn:@"lastdate"];
        NSString *wdate = [resultSet stringForColumn:@"wdate"];
        NSString *bbsname = [resultSet stringForColumn:@"bbsname"];
        HotPost *model = [[HotPost alloc] init];
        model.title = title;
        model.photo = photo;
        model.nickname = nickname;
        model.reply = reply;
        model.lastdate = lastdate;
        model.wdate = wdate;
        model.bbsname = bbsname;
        [_dataSourceArray addObject:model];
    }
    [resultSet close];
}

- (void)requestDataWithType:(NSInteger)type
{
    if (type == 1) {
        _page ++;
    }
    else
    {
        _page = 1;
    }
   NSString *str1 = [NSString stringWithFormat:@"http://lib.wap.zol.com.cn/bbs/ios/getHotBook.php?page=%d&userid=&vs=440",_page];
    [PKRequestManager requestWithType:GET urlString:str1 parDic:nil finish:^(NSData *data) {
        [_dataBase executeUpdate:@"DELETE FROM HOTPOST"];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        if (type == 0) {
            [self.dataSourceArray removeAllObjects];
        }
        NSArray *listArray = dic[@"hotList"];
        for (NSDictionary *moDic in listArray) {
            HotPost *model = [[HotPost alloc] init];
            [model setValuesForKeysWithDictionary:moDic];
            [_dataSourceArray addObject:model];
            [_dataBase executeUpdate:@"INSERT INTO HOTPOST (title,photo,nickname,reply,lastdate,wdate,bbsname) VALUES (?,?,?,?,?,?,?)",model.title,model.photo,model.nickname,model.reply,model.lastdate,model.wdate,model.bbsname];
        }
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"页面请求失败");
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return _dataSourceArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HotPost *model = _dataSourceArray[indexPath.row];
        
    
    HotPostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.titleLabel.text = model.title;
    [cell.authorImg sd_setImageWithURL:[NSURL URLWithString:model.photo]];
    cell.authorNameLabel.text = model.nickname;
    NSString *str = [NSString stringWithFormat:@"%@",model.reply];
    cell.replyLabel.text = [str stringByAppendingString:@"：回复"];
    NSString *string = model.lastdate;
    cell.replyTimeLabel.text = [string substringFromIndex:10];
    NSString *timStr = model.wdate;
    cell.timeLabel.text = [timStr substringToIndex:10];
    cell.typeName.text = model.bbsname;
    cell.supportLabel.text = [NSString stringWithFormat:@"%@",model.favourNum];
    
    DFSignlTon *signlTon = [DFSignlTon shareInstance];
    if (signlTon.savemode == SaveModeYes)
    {
        cell.aImage.image = [UIImage imageNamed:@""];
        cell.bImage.image = [UIImage imageNamed:@""];
        cell.cImage.image = [UIImage imageNamed:@""];
    }else
    {
        if (model.picArray.count == 1) {
            [cell.aImage sd_setImageWithURL:[NSURL URLWithString:model.picArray[0]]];
            cell.bImage.image = [UIImage imageNamed:@"white"];
            cell.cImage.image = [UIImage imageNamed:@"white"];
        }
        if(model.picArray.count == 2){
            [cell.aImage sd_setImageWithURL:[NSURL URLWithString:model.picArray[0]]];
            [cell.bImage sd_setImageWithURL:[NSURL URLWithString:model.picArray[1]]];
            cell.cImage.image = [UIImage imageNamed:@"white"];
        }
        if(model.picArray.count == 3){
            [cell.aImage sd_setImageWithURL:[NSURL URLWithString:model.picArray[0]]];
            [cell.bImage sd_setImageWithURL:[NSURL URLWithString:model.picArray[1]]];
            [cell.cImage sd_setImageWithURL:[NSURL URLWithString:model.picArray[2]]];
        }
;
    }

    
    
    if ([model.good isEqualToString:@"3"]) {
        cell.fireImg.image = [UIImage imageNamed:@"fire"];
        cell.fireLabelImg.image = [UIImage imageNamed:@"stars"];
    }
    else if ([model.good isEqualToString:@"2"]) {
        cell.fireImg.image = [UIImage imageNamed:@"fire"];
        cell.fireLabelImg.image = [UIImage imageNamed:@"two"];

    }
    else
    {
        cell.fireImg.image = [UIImage imageNamed:@"white"];
        cell.fireLabelImg.image = [UIImage imageNamed:@"white"];
    }
    
    return cell;
        

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DFwebViewController *webVC = [[DFwebViewController alloc] init];
    HotPost *model = _dataSourceArray[indexPath.row];
    webVC.astr = model.bbs;
    webVC.bstr = model.boardid;
    webVC.cstr = model.bookid;
    [self.navigationController pushViewController:webVC animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
